"""
    Author:
    Date: 2018-10-31

    微信管理后台-GM管理页面
"""

from django.shortcuts import render
from django.urls import reverse

from entities import gm_mgr

from utils.log import Log
from utils.wx_util import WechatApi

from .. import helpers
from .. helpers import gma_login_required


@gma_login_required
def index(request):
    """ GM用户列表 """
    context = helpers.build_context(request)
    context['username'] = request.user.username if request.user.username else 'test'
    context['users'] = gm_mgr.get_gm_list(100)
    context['total_count'] = gm_mgr.get_gm_count()
    return render(request, 'gma/gm/gm_list.html', context)


@gma_login_required
def detail(request, uid):
    """ GM用户详情 """
    user = gm_mgr.get_gm_detail(uid)
    permissions = gm_mgr.get_gm_permission_detail(user['permission'])
    for key, value in permissions.items():
        value['checked'] = 'checked="checked"' if value['open'] else ''

    context = helpers.build_context(request)
    context['username'] = request.user.username
    context['user'] = user
    context['level_desp'] = gm_mgr.get_gm_level_desp(user['level'])
    context['permissions'] = permissions
    return render(request, 'gma/gm/gm_detail.html', context)


@gma_login_required
def set_gm_level(request, uid, level):
    """ 设置GM权限等级 """
    uid = int(uid)
    level = int(level)

    gm = gm_mgr.get_gm_detail(uid)
    if gm is None:
        return helpers.show_warn_page(request, '该用户已不存在！')

    inviter_openid = helpers.get_request_openid(request)
    operator = gm_mgr.get_gm_detail_by_openid(inviter_openid)
    if operator is None:
        return helpers.show_warn_page(request, '系统错误！')

    # 只能操作权限等级比自己低的用户
    if gm['level'] >= operator['level']:
        return helpers.show_warn_page(request, '对方的权限等级过高，无法设置！')

    # 设置的权限等级不能等于我大于自己的权限等级
    if level >= operator['level']:
        return helpers.show_warn_page(request, '权限不足，无法设置！')

    # 设置权限
    nickname = gm['nickname']
    success = gm_mgr.set_gm_level(uid, level)
    if not success:
        Log.error(f'Set gm level failed: uid={uid}, level={level}, admin={request.user.username}')
        return helpers.show_warn_page(request, f'{nickname}的GM权限等级设置失败!')

    Log.info(f'Set gm level ok: uid={uid}, level={level}, admin={request.user.username}')
    redirect_url = reverse('gma:gm_detail', kwargs={'uid': uid})
    return helpers.show_success_page(request, f'成功将<a>{nickname}</a>的GM权限设置成了<a>{level}</a>级!', redirect_url)


@gma_login_required
def delete(request, uid):
    """ 删除GM """
    uid = int(uid)
    gm = gm_mgr.get_gm_detail(uid)
    nickname = gm['nickname']

    success = gm_mgr.delete_gm(uid)
    if not success:
        Log.error(f'Delete gm failed: uid={uid}, admin={request.user.username}')
        return helpers.show_warn_page(request, f'删除GM <a>{nickname}</a>失败!')

    Log.info(f'Delete gm ok: uid={uid}, admin={request.user.username}')
    redirect_url = reverse('gma:gm')
    return helpers.show_success_page(request, f'成功删除GM <a>{nickname}</a>!', redirect_url)


@gma_login_required
def show_invite_gm_qr(request, inviter):
    """ 显示邀请GM的二维码 """
    qr_url = WechatApi.get_qr_code_show_url(f'invite-gm:{inviter}')
    if qr_url is None:
        return helpers.show_warn_page(request, '创建邀请管理员的二维码失败!')

    context = helpers.build_context(request)
    context['username'] = request.user.username
    context['qr_url'] = qr_url
    return render(request, 'gma/gm/show_invite_qr.html', context)


if __name__ == '__main__':
    print('ok')
